<template>
  <div class="cs-p">
    <el-form
      :inline="true"
      size="small">

      <el-form-item >
        <el-button
          v-if="isAuth('sys:group:save')"
          icon="el-icon-plus"
          :disabled="loading"
          @click="handleCreate">新增用户组</el-button>
      </el-form-item>

      <el-form-item>
        <el-button-group>
          <el-button
            v-if="auth.enable"
            icon="el-icon-check"
            :disabled="loading"
            @click="handleState(1)">启用</el-button>

          <el-button
            v-if="auth.disable"
            icon="el-icon-close"
            :disabled="loading"
            @click="handleState(0)">禁用</el-button>
        </el-button-group>
      </el-form-item>

      <cs-help
        :router="$route.path"
        style="padding-bottom: 19px;">
      </cs-help>
    </el-form>

    <cs-table :table-data="currentTableData"
              :table-label="tableLabel"
              @handleButton="handleButton"
              @handleSortChange="handleSortChange"
              @handleSelectionChange="handleSelectionChange"
              :table-option="tableOption">
      <template slot="status" slot-scope="scope">
        <el-tag v-if="scope.row.status===0">启用</el-tag>
        <el-tag v-if="scope.row.status===1" type="success">禁用</el-tag>
      </template>
    </cs-table>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="600px">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="80px">
        <el-form-item
          label="名称"
          prop="roleName">
          <el-input
            v-model="form.roleName"
            placeholder="请输入名称"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="描述"
          prop="description">
          <el-input
            v-model="form.description"
            placeholder="可输入描述"
            type="textarea"
            :rows="5"/>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item
              label="排序值"
              prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
                :max="255"
                style="width: 120px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="状态"
              prop="status">
              <el-switch
                v-model="form.status"
                active-value="0"
                inactive-value="1">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="菜单权限"
          prop="menuIds">
          <el-tree
            node-key="id"
            :data="menuData"
            :props="treeProps"
            :show-checkbox="true"
            ref="menuTree">
              <span class="custom-tree-node" slot-scope="{node, data}">
                <span class="brother-showing" :class="{'status-tree': !data.status}">
                  <i v-if="data.icon" :class="`iconfont icon${data.icon}`"/>
                  <i v-else-if="data.children" :class="`el-icon-${node.expanded ? 'folder-opened' : 'folder'}`"/>
                  <i v-else class="el-icon-document"/>
                  {{node.label}}
                  <i v-if="data.url" class="el-icon-link">
                    {{data.url}}
                  </i>
                </span>
              </span>
          </el-tree>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          @click="dialogFormVisible = false"
          size="small">取消</el-button>

        <el-button
          v-if="dialogStatus === 'create'"
          type="primary"
          :loading="dialogLoading"
          @click="create"
          size="small">确定</el-button>

        <el-button
          v-else type="primary"
          :loading="dialogLoading"
          @click="update(form.index)"
          size="small">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addAuthGroupItem,
  setAuthGroupItem,
  delAuthGroupItem,
  setAuthGroupSort,
  setAuthGroupStatus
} from '@/api/auth/group'
import util from '@/utils/util'
import { getMenuList } from '@/api/auth/menu'

export default {
  components: {
    'CsTable': () => import('@/components/cs-table')
  },
  props: {
    tableData: {
      default: () => []
    },
    loading: {
      default: false
    }
  },
  data() {
    return {
      tableLabel: [
        { label: '名称', param: 'roleName', align: 'center', sortable: false, isShow: true },
        { label: '描述', param: 'description', align: 'center', isShow: true },
        { label: '排序', param: 'sort', align: 'center', sortable: false, isShow: true },
        { label: '状态', param: 'status', align: 'center', sortable: false, slot: true, isShow: true }
      ],
      tableOption: {
        label: '操作',
        width: '200',
        options: [
          { label: '编辑', type: 'primary', icon: 'el-icon-edit', methods: 'audit', auth: 'sys:group:update' },
          { label: '删除', type: 'danger', icon: 'el-icon-delete', methods: 'delete', auth: 'sys:group:delete' }
        ]
      },
      currentTableData: [],
      multipleSelection: [],
      auth: {
        add: true,
        del: true,
        set: true,
        enable: false,
        disable: false,
        sort: true
      },
      treeLoading: false,
      treeProps: {
        label: 'name',
        children: 'children'
      },
      dialogLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户组',
        create: '新增用户组'
      },
      menuData: [],
      form: {
        roleId: undefined,
        roleName: undefined,
        description: undefined,
        sort: undefined,
        status: '0',
        menuIds: []
      },
      rules: {
        roleName: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          },
          {
            max: 32,
            message: '长度不能大于 32 个字符',
            trigger: 'blur'
          }
        ],
        description: [
          {
            max: 255,
            message: '长度不能大于 255 个字符',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            type: 'number',
            message: '必须为数字值',
            trigger: 'blur'
          }
        ],
        status: [
          {
            type: 'enum',
            enum: ['0', '1'],
            message: '值的范围必须为 0 或 1',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    tableData: {
      handler(val) {
        this.currentTableData = val
      },
      immediate: true
    }
  },
  created() {
    this.loadMenuList()
  },
  mounted() {
    this._validationAuth()
  },
  methods: {
    // 验证权限
    _validationAuth() {
      this.auth.add = this.$permission('/system/auth/group/add')
      this.auth.del = this.$permission('/system/auth/group/del')
      this.auth.set = this.$permission('/system/auth/group/set')
      this.auth.enable = this.$permission('/system/auth/group/enable')
      this.auth.disable = this.$permission('/system/auth/group/disable')
      this.auth.sort = this.$permission('/system/auth/group/sort')
    },
    // 菜单数据
    loadMenuList() {
      this.treeLoading = true
      getMenuList()
        .then(res => {
          this.menuData = util.formatDataToTree(res.data)
        })
        .finally(() => {
          this.treeLoading = false
        })
    },
    handleButton(methods, row, index) {
      // 修改
      if (methods.methods === 'audit') {
        this.handleUpdate(methods.index)
      } else if (methods.methods === 'delete') { // 删除
        this.handleDelete(methods.index)
      }
    },
    // 排序
    handleSortChange(val) {
    },
    // 选中数据项
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取排序字段
    sortChange({ column, prop, order }) {
      let sort = {
        order_type: undefined,
        order_field: undefined
      }

      if (column && order) {
        sort.order_type = order === 'ascending' ? 'asc' : 'desc'
        sort.order_field = prop
      }

      this.$emit('sort', sort)
    },
    // 返回表格行颜色
    tableRowClassName({ row }) {
      if (row.system) {
        return 'warning-row'
      }
      return ''
    },
    // 弹出新建对话框
    handleCreate() {
      this.form = {
        index: undefined,
        name: '',
        description: '',
        sort: 50,
        status: '0',
        menuIds: []
      }

      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
          this.$refs.menuTree.setCheckedKeys([])
        }
        this.dialogStatus = 'create'
        this.dialogLoading = false
        this.dialogFormVisible = true
      })
    },
    // 获取勾选节点
    _getCheckedKeys() {
      this.form.menuIds = [
        ...this.$refs.menuTree.getCheckedKeys(),
        ...this.$refs.menuTree.getHalfCheckedKeys()
      ]
    },
    // 请求创建用户组
    create() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          this._getCheckedKeys()
          addAuthGroupItem({ ...this.form })
            .then(res => {
              // this.currentTableData.unshift(res.data)
              this.dialogFormVisible = false
              this.$emit('refresh')
              // this.$message.success('操作成功')
            })
            .catch(() => {
              this.dialogLoading = false
            })
        }
      })
    },
    // 批量设置状态
    handleState(state) {
      let group_list = []
      this.multipleSelection.forEach(value => {
        group_list.push(value.group_id)
      })

      if (group_list.length === 0) {
        this.$message.error('请选择要操作的数据')
        return
      }

      this.$confirm('确定要执行该操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          setAuthGroupStatus(group_list, state)
            .then(() => {
              this.currentTableData.forEach((value, index) => {
                if (group_list.indexOf(value.group_id) !== -1) {
                  this.$set(this.currentTableData, index, {
                    ...value,
                    status: state
                  })
                }
              })

              this.$message.success('操作成功')
            })
        })
        .catch(() => {
        })
    },
    // 角色菜单数据处理
    getRoleMens(menuData) {
      let checked = [] // 需要选中的节点
      let pidArr = [] // 获取父节点
      for (let item of menuData) {
        pidArr.push(item.parentId)
      }

      for (let item of menuData) {
        let id = item.id
        let menuId = item.menuId
        let isP = pidArr.includes(menuId)
        if (!isP) {
          checked.push(id)
        }
      }
      return checked
    },
    // 弹出编辑对话框
    handleUpdate(index) {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
          this.$refs.menuTree.setCheckedKeys([])
        }
        this.form = {
          index: index,
          roleId: this.currentTableData[index].roleId,
          roleName: this.currentTableData[index].roleName,
          description: this.currentTableData[index].description,
          sort: this.currentTableData[index].sort,
          status: this.currentTableData[index].status.toString()
        }
        this.form.menuIds = this.getRoleMens(this.currentTableData[index].menuList)
        this.dialogStatus = 'update'
        this.dialogLoading = false
        this.dialogFormVisible = true
        setTimeout(() => {
          this.$refs.menuTree.setCheckedKeys(this.form.menuIds, false)
        }, 500)
      })
    },
    // 请求修改用户组
    update(index) {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          this._getCheckedKeys()
          setAuthGroupItem({ ...this.form })
            .then(res => {
              // this.$set(this.currentTableData, index, {
              //   ...this.currentTableData[index]
              // })
              this.$emit('refresh')
              this.dialogFormVisible = false
              // this.$message.success('操作成功')
            })
            .catch(() => {
              this.dialogLoading = false
            })
        }
      })
    },
    // 请求删除用户组
    handleDelete(index) {
      this.$confirm('确定要执行该操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          delAuthGroupItem(this.currentTableData[index].roleId)
            .then(() => {
              this.$emit('refresh')
              // this.currentTableData.splice(index, 1)
              // this.$message.success('操作成功')
            })
        })
        .catch(() => {
        })
    },
    // 请求修改排序值
    handleSort(index) {
      setAuthGroupSort(
        this.currentTableData[index].group_id,
        this.currentTableData[index].sort
      )
    },
    // 请求修改状态值
    switchStatus(index) {
      let oldData = this.currentTableData[index]
      const newStatus = oldData.status ? 0 : 1

      // 禁用权限检测
      if (newStatus === 0 && !this.auth.disable) {
        return
      }

      // 启用权限检测
      if (newStatus === 1 && !this.auth.enable) {
        return
      }

      this.$set(this.currentTableData, index, { ...oldData, status: 2 })
      setAuthGroupStatus([oldData.group_id], newStatus)
        .then(() => {
          this.$message.success('操作成功')
          this.$set(this.currentTableData, index, {
            ...oldData,
            status: newStatus
          })
        })
        .catch(() => {
          this.$set(this.currentTableData, index, oldData)
        })
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .spacer-row {
    background: #FAFAFA;
  }
</style>
